<template>
  <view class="page-container">
    <uni-nav-bar title="切换店铺" left-icon="back" fixed @click-left="goBack" />

    <view class="content">
      <!-- 当前登录店铺 -->
      <view class="section">
        <view class="section-header">
          <view class="section-title">当前登录店铺</view>
        </view>
        <view class="store-item current">
          <view class="store-name">{{
            currentStore.merchantName || "暂无"
          }}</view>
          <view v-if="currentStore.storeAddress" class="store-address">
            {{ currentStore.storeAddress }}
          </view>
        </view>
      </view>

      <!-- 选择店铺 -->
      <view class="section">
        <view class="section-header">
          <view class="section-title">选择店铺</view>
        </view>

        <!-- 加载中状态 -->
        <view v-if="loading" class="loading-state">
          <uni-load-more status="loading" />
        </view>

        <!-- 有店铺列表时显示 -->
        <scroll-view
          v-else-if="storeList.length > 0"
          class="store-list"
          scroll-y
          :scroll-top="scrollTop"
          @scrolltolower="handleScrollToLower"
        >
          <view
            v-for="store in storeList"
            :key="store.id"
            class="store-item"
            @click="switchStore(store)"
          >
            <view class="store-name">{{ store.merchantName }}</view>
            <view v-if="store.storeAddress" class="store-address">
              {{ store.storeAddress }}
            </view>
          </view>

          <!-- 触底加载组件 -->
          <LoadMore
            v-if="storeList.length > 0"
            :status="loadMoreStatus"
            @retry="handleLoadMore"
          />
        </scroll-view>

        <!-- 无店铺时显示空状态 -->
        <view v-else class="empty-state">
          <view class="empty-icon">
            <uni-icons type="shop" color="#d8d8d8" size="100"></uni-icons>
          </view>
          <view class="empty-text">~暂无可选店铺~</view>
        </view>
      </view>
    </view>
  </view>
  <view class="btn pos-fixed w-100% h-120rpx bottom-0">
    <view
      @click="goToAddStore"
      class="bg-#ffbb00 rounded-50rpx mx16rpx h-88rpx line-height-88rpx text-center color-#fff"
    >
      新增店铺
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from "vue";
import { useRequest } from "ahooks-vue";
import { getStoreList, switchStore as switchStoreApi } from "@/api/user";
import { useStoreStore } from "@/store/modules/store";
import { useUserStore } from "@/store/modules/user";
import LoadMore from "@/components/common/LoadMore/LoadMore.vue";

// 使用 Pinia store
const storeStore = useStoreStore();
const userStore = useUserStore();

// 当前店铺信息（从 store 获取）
const currentStore = computed(() => storeStore.currentStore || {});

console.log("switchStore 页面初始化");
console.log("当前店铺信息:", currentStore.value);
console.log("当前店铺ID:", storeStore.storeId);

// 所有店铺列表
const allStoreList = ref([]);

// 可选店铺列表（排除当前登录的店铺）
const storeList = computed(() => {
  const currentStoreId = storeStore.storeId;
  if (!currentStoreId) {
    return allStoreList.value;
  }
  // 过滤掉当前登录的店铺
  return allStoreList.value.filter((store) => store.id !== currentStoreId);
});

const scrollTop = ref(0); // 滚动位置

// 分页参数
const pageParams = ref({
  offset: 1,
  limit: 10,
});

// 是否有更多数据
const hasMore = ref(true);

// 加载更多状态：loading-加载中, nomore-没有更多, error-加载失败, more-可以加载更多
const loadMoreStatus = ref("more");

// 获取店铺列表
const { loading, run: getStoreListRun } = useRequest(
  (params) =>
    getStoreList({
      userId: userStore.userId,
      ...params,
    }),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("店铺列表获取成功：", response);

      // 接口返回格式：{ code: 2000, message: '操作成功', data: [...] }
      const data = response?.data || [];

      if (data && data.length > 0) {
        // 如果是第一页，直接赋值；否则追加
        if (pageParams.value.offset === 1) {
          allStoreList.value = data;
        } else {
          allStoreList.value = [...allStoreList.value, ...data];
        }

        // 判断是否还有更多数据
        if (data.length < pageParams.value.limit) {
          hasMore.value = false;
          loadMoreStatus.value = "nomore";
        } else {
          hasMore.value = true;
          loadMoreStatus.value = "more";
        }
      } else {
        // 没有数据
        if (pageParams.value.offset === 1) {
          allStoreList.value = [];
        }
        hasMore.value = false;
        loadMoreStatus.value = "nomore";
      }
    },
    onError: (error) => {
      console.error("获取店铺列表失败：", error);
      loadMoreStatus.value = "error";
      uni.showToast({
        title: "获取店铺列表失败",
        icon: "none",
      });
    },
  }
);

// 初始化加载
const initLoad = () => {
  pageParams.value.offset = 1;
  hasMore.value = true;
  loadMoreStatus.value = "more";
  getStoreListRun(pageParams.value);
};

// 加载更多
const handleLoadMore = () => {
  if (loading.value || !hasMore.value) return;

  loadMoreStatus.value = "loading";
  pageParams.value.offset += 1;
  getStoreListRun(pageParams.value);
};

// 触底加载
const handleScrollToLower = () => {
  handleLoadMore();
};

// 返回上一页
const goBack = () => {
  uni.navigateBack();
};

const goToAddStore = () => {
  uni.navigateTo({
    url: "/pages/login/partner/partner",
  });
};

// 切换店铺加载状态
const switchLoading = ref(false);

// 调用切换店铺接口
const { run: switchStoreRun } = useRequest(
  (data) => switchStoreApi(data),
  {
    manual: true,
    onSuccess: (response) => {
      console.log("切换店铺接口调用成功：", response);

      uni.showToast({
        title: "切换成功",
        icon: "none",
        duration: 1000,
      });

      // 切换成功后跳转到首页
      setTimeout(() => {
        switchLoading.value = false;
        uni.switchTab({
          url: "/pages/index/index",
        });
      }, 1000);
    },
    onError: (error) => {
      console.error("切换店铺接口调用失败：", error);
      switchLoading.value = false;
      uni.showToast({
        title: "切换店铺失败",
        icon: "none",
      });
    },
  }
);

// 切换店铺
const switchStore = (store) => {
  if (switchLoading.value) return;

  uni.showModal({
    title: "切换店铺",
    content: `确认切换到 ${store.merchantName} 吗？`,
    confirmColor: "#ffbb00",
    success: (res) => {
      if (res.confirm) {
        switchLoading.value = true;

        // 使用 Pinia 保存店铺信息
        storeStore.setStoreInfo(store);
        console.log("✅ 店铺信息已更新:", store.merchantName);

        // 调用切换店铺接口
        switchStoreRun({
          merchantId: store.id,
          userId: userStore.userId,
        });
      }
    },
  });
};

// 生命周期
onMounted(() => {
  // 初始化加载店铺列表
  if (userStore.userId) {
    initLoad();
  } else {
    console.warn("缺少用户ID，无法加载店铺列表");
    uni.showToast({
      title: "缺少用户信息，请先登录",
      icon: "none",
    });
  }
});
</script>

<style lang="scss" scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f5f5;
}

.content {
  padding: 20rpx 32rpx;
}

.section {
  margin-bottom: 40rpx;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 8rpx;
  margin-bottom: 16rpx;
}

.section-title {
  font-size: 28rpx;
  color: #333;
  font-weight: 500;
}
.store-item {
  background-color: #fff;
  padding: 32rpx;
  border-radius: 12rpx;
  margin-bottom: 16rpx;

  &:last-child {
    margin-bottom: 0;
  }

  &.current {
    border: 2rpx solid #ffbb00;
  }
}

.store-name {
  font-size: 28rpx;
  color: #333;
  text-align: center;
  margin-bottom: 8rpx;
}

.store-address {
  font-size: 24rpx;
  color: #999;
  text-align: center;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.store-list {
  flex: 1;
  height: 500rpx;

  .store-item {
    cursor: pointer;
    transition: background-color 0.3s;

    &:active {
      background-color: #f8f8f8;
    }
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  background-color: #fff;
  border-radius: 12rpx;
}

.empty-state {
  background-color: #fff;
  padding: 80rpx 32rpx;
  border-radius: 12rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.empty-icon {
  margin-bottom: 24rpx;
  opacity: 0.3;
}

.empty-text {
  font-size: 28rpx;
  color: #999;
}
</style>
